import AxiosInstance from "../utils/axios-instance";
import axiosInstance from "../utils/axios-instance";

export default {
    emptyStringToNull(string) {
        if (string != null && string.length === 0) {
            return null
        }
        return string
    },

    getLocations(targetId, routeId, page = 0, size = 20) {
        targetId = this.emptyStringToNull(targetId)
        routeId = this.emptyStringToNull(routeId)
        if (routeId != null && routeId.length === 0) {
            routeId = null
        }

        if (targetId != null && routeId != null) {
            return AxiosInstance.get(
                "/track" +
                "?targetId=" + targetId +
                "&routeId=" + routeId +
                "&page=" + page +
                "&size=" + size
            ).then(response => {
                return response.data
            })
        } else if (targetId != null) {
            return AxiosInstance.get(
                "/track" +
                "?targetId=" + targetId +
                "&page=" + page +
                "&size=" + size
            ).then(response => {
                return response.data
            })
        } else if (routeId != null) {
            return AxiosInstance.get(
                "/track" +
                "?routeId=" + routeId +
                "&page=" + page +
                "&size=" + size
            ).then(response => {
                return response.data
            })
        } else {
            return AxiosInstance.get(
                "/track" +
                "?page=" + page +
                "&size=" + size
            ).then(response => {
                return response.data
            })
        }
    },

    getEasyDlResults(logId, page = 0, size = 20) {
        if (logId != null) {
            // 确保logId作为字符串处理
            const stringLogId = String(logId);
            console.log('获取单个结果 - 原始logId:', logId);
            console.log('获取单个结果 - 处理后stringLogId:', stringLogId);
            
            return AxiosInstance.get(
                "/easyDlResults/" + stringLogId
            ).then(response => {
                return response.data
            })
        } else {
            return AxiosInstance.get(
                "/easyDlResults" +
                "?page=" + page +
                "&size=" + size +
                "&sort=recognitionTime,desc"
            ).then(response => {
                console.log('获取列表结果 - 原始响应数据:', response.data);
                
                // 检查log_id是否正确保存
                if (response.data && response.data._embedded && response.data._embedded.easyDlResults) {
                    for (let i = 0; i < response.data._embedded.easyDlResults.length; i++) {
                        const item = response.data._embedded.easyDlResults[i];
                        if (item.log_id) {
                            console.log(`结果项[${i}] log_id类型:`, typeof item.log_id);
                            console.log(`结果项[${i}] log_id值:`, String(item.log_id));
                        }
                    }
                }
                
                let easyDlResults = response.data._embedded.easyDlResults
                for (let i = 0; i < response.data._embedded.easyDlResults.length; i++) {
                    if (easyDlResults[i].results == null) {
                        continue;
                    }

                    let resultScore = [];
                    for (let j = 0; j < easyDlResults[i].results.length; j++) {
                        let name = easyDlResults[i].results[j].name

                        if (name === "采血管") {
                            resultScore[0] = easyDlResults[i].results[j].score.toFixed(6)
                        }
                        if (name === "注射器") {
                            resultScore[1] = easyDlResults[i].results[j].score.toFixed(6)
                        }
                        if (name === "西林瓶") {
                            resultScore[2] = easyDlResults[i].results[j].score.toFixed(6)
                        }
                        if (name === "手套") {
                            resultScore[3] = easyDlResults[i].results[j].score.toFixed(6)
                        }
                        if (name === "口罩") {
                            resultScore[4] = easyDlResults[i].results[j].score.toFixed(6)
                        }
                    }
                      // 处理sort_result_name为null或空的情况
                      if (!easyDlResults[i].sort_result_name || easyDlResults[i].sort_result_name === "") {
                        // 找出score最高的结果
                        let maxScore = -1;
                        let maxScoreItem = null;
                        
                        for (let j = 0; j < easyDlResults[i].results.length; j++) {
                            const result = easyDlResults[i].results[j];
                            if (result.score > maxScore) {
                                maxScore = result.score;
                                maxScoreItem = result;
                            }
                        }
                        
                        // 如果找到最高分数的项，将其name设为sort_result_name
                        if (maxScoreItem) {
                            easyDlResults[i].sort_result_name = maxScoreItem.name;
                        }
                    }   
                    response.data._embedded.easyDlResults[i].resultScore = resultScore;
                }
                return response.data
            })
        }
    },

    async deleteLocation(locationId) {
        try {
            const response = await AxiosInstance.delete("/locations/" + locationId)
            if (response.status === 200 || response.status === 204) {
                return true
            } else {
                throw new Error('删除失败: ' + response.status)
            }
        } catch (error) {
            console.error('Delete error:', error)
            throw error
        }
    },

    deleteLocationsAll() {
        return axiosInstance.delete("/extension/locations/all")
    },

    // 获取路径列表
    getRoutes(url = '/routes') {
        return AxiosInstance.get(url)
    },

    // 获取路径详情
    getRouteDetail(routeId) {
        return AxiosInstance.get(`/routes/${routeId}`)
    },

    // 创建新路径
    createRoute(data) {
        return AxiosInstance.post('/routes', data)
    },

    // 更新路径
    updateRoute(routeId, data) {
        return AxiosInstance.put(`/routes/${routeId}`, data)
    },

    // 删除路径
    deleteRoute(routeId) {
        return AxiosInstance.delete(`/routes/${routeId}`)
    },

    // 获取每日统计数据
    getDailyStatistics(startDate, endDate) {
        let url = '/statistics/daily-count'
        if (startDate && endDate) {
            url += `?startDate=${startDate}&endDate=${endDate}`
        }
        console.log('请求URL:', url)
        return AxiosInstance.get(url).then(response => {
            console.log('API响应:', response)
            return response.data
        }).catch(error => {
            console.error('API错误:', error)
            throw error
        })
    },

    // 获取医疗废物类型统计数据
    getWasteTypeStatistics(startDate, endDate, types = null) {
        let url = '/statistics/waste-types'
        
        const params = []
        if (startDate && endDate) {
            params.push(`startDate=${startDate}`)
            params.push(`endDate=${endDate}`)
        }
        
        if (types && Array.isArray(types) && types.length > 0) {
            params.push(`types=${types.join(',')}`)
        }
        
        if (params.length > 0) {
            url += '?' + params.join('&')
        }
        
        console.log('请求URL:', url)
        return AxiosInstance.get(url).then(response => {
            console.log('API响应:', response)
            return response.data
        }).catch(error => {
            console.error('API错误:', error)
            throw error
        })
    },

    // 获取分类图片
    getClassificationImage(logId) {
        // 确保logId作为字符串处理，避免精度丢失
        const stringLogId = String(logId);
        console.log('获取图片URL - 转换前logId:', logId);
        console.log('获取图片URL - 转换后stringLogId:', stringLogId);
        
        // 使用配置中的baseURL，确保请求指向后端服务器
        const baseURL = AxiosInstance.defaults.baseURL;
        return `${baseURL}/api/classification/image/download/${stringLogId}`
    }
}